﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace Warensoft.Unity.Communication.Client.DbClient
{
    /// <summary>
    /// data base parameter 
    /// </summary>

    public class WDbParameter
    {
        /// <summary>
        /// 参数名称
        /// </summary>
        public string ParameterName { get; set; }
        /// <summary>
        /// 参数值
        /// </summary>
        public object Value { get; set; }

        public WDbParameter(byte[] buffer)
        {
            this.Fill(buffer);
        }
        public WDbParameter()
        { }
        public byte[] ToArray()
        {
            byte[] buffer = null;
            using (MemoryStream ms = new MemoryStream())
            {
                using (BinaryWriter bw = new BinaryWriter(ms))
                {
                    bw.Write(this.ParameterName);
                    using (MemoryStream ms1 = new MemoryStream())
                    {
                        BinaryFormatter bf = new BinaryFormatter();
                        bf.Serialize(ms1, this.Value);
                        var tempBuffer = ms1.ToArray();
                        bw.Write(tempBuffer.Length);
                        bw.Write(tempBuffer, 0, tempBuffer.Length);
                    }

                }
                buffer = ms.ToArray();
            }
            return buffer;
        }


        protected void Fill(byte[] buffer)
        {
            using (MemoryStream ms = new MemoryStream(buffer))
            {
                using (BinaryReader br = new BinaryReader(ms))
                {
                    this.ParameterName = br.ReadString();
                    int bufferLength = br.ReadInt32();

                    byte[] valueBuffer = br.ReadBytes(bufferLength);
                    using (MemoryStream ms1 = new MemoryStream(valueBuffer))
                    {
                        BinaryFormatter bf = new BinaryFormatter();
                        this.Value = bf.Deserialize(ms1);
                    }
                }
            }
        }
    }
}
